<template>
  <div class="login">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
    >
      <h3 class="title">认证中心</h3>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="账号密码登录" name="first"></el-tab-pane>
        <el-tab-pane label="钉钉扫码登录" name="second"></el-tab-pane>
      </el-tabs>
      <div v-show="isLogin">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" type="text" placeholder="账号">
            <svg-icon
              slot="prefix"
              icon-class="user"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon
              slot="prefix"
              icon-class="password"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            v-model="loginForm.code"
            placeholder="验证码"
            style="width: 63%"
            v-show="isMobile"
          >
          </el-input>
          <div class="login-code" v-show="isMobile">
            <img :src="codeUrl" @click="getCode" class="login-code-img" />
          </div>
          <verify
            ref="verify"
            class="verify-con"
            verifyType="LOGIN"
            @change="verifyChange"
            v-show="!isMobile"
          ></verify>
        </el-form-item>
        <el-checkbox
          v-model="loginForm.rememberMe"
          style="margin: 0px 0px 25px 0px"
          >记住密码</el-checkbox
        >
        <el-form-item style="width: 100%">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            style="width: 100%"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
        </el-form-item>
      </div>
      <div v-show="!isLogin" style="width: 100%; height: 229px">
        <div id="self_defined_element" class="self-defined-classname"></div>
      </div>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2021-2022 fkmalls.com All Rights Reserved.</span>
    </div>
    <!-- 背景图 -->
    <vue-particles
      color="#409EFF"
      :particleOpacity="0.7"
      :particlesNumber="60"
      shapeType="circle"
      :particleSize="6"
      linesColor="#409EFF"
      :linesWidth="1"
      :lineLinked="true"
      :lineOpacity="0.4"
      :linesDistance="150"
      :moveSpeed="3"
      :hoverEffect="true"
      hoverMode="grab"
      :clickEffect="true"
      clickMode="push"
    >
    </vue-particles>
    <div class="logo">
      <img src="../assets/images/fkmalls.png" />
    </div>
  </div>
</template>
<script src="https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js"></script>
<script>
import { getCodeImg } from "@/api/login"
import Cookies from "js-cookie"
import { encrypt, decrypt } from "@/utils/jsencrypt"
import verify from "@/views/components/verify"
import { getUserInfo } from "@/api/ddlogin/dd"
import { setToken } from "@/utils/auth"
import { isMobile } from "@/utils/fkmalls"

export default {
  components: {
    verify,
  },
  name: "Login",
  data() {
    return {
      isLogin: true,
      activeName: "first",
      isMobile: false,
      codeUrl: "",
      cookiePassword: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" },
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" },
        ],
        // code: [{ required: true, trigger: "change", message: "验证码不能为空" }]
      },
      loading: false,
      redirect: undefined,
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true,
    },
  },
  created() {
    // this.isMobile = isMobile();
    this.getCode()
    this.getCookie()
  },
  mounted() {
    this.ddNewLogin()
  },
  methods: {
    async handleCodeLogin(code) {
      const res = await getUserInfo(code)
      setToken(res.data.access_token)
      this.$router.push({ path: this.redirect || "/" }).catch(() => {})
    },
    ddNewLogin() {
      window.DTFrameLogin(
        {
          id: "self_defined_element",
          width: 300,
          height: 300,
        },
        {
          redirect_uri: encodeURIComponent("https://sys.fkmalls.com/login"),
          client_id: "ding8sugpunwvgg5rnjy",
          scope: "openid",
          response_type: "code",
          state: "STATE",
          prompt: "consent",
        },
        (loginResult) => {
          const { redirectUrl, authCode, state } = loginResult
          // 这里可以直接进行重定向
          // window.location.href = redirectUrl;
          // 也可以在不跳转页面的情况下，使用code进行授权
          console.log(redirectUrl, authCode, state)
          this.handleCodeLogin(authCode)
        },
        (errorMsg) => {
          alert(`Login Error: ${errorMsg}`)
        }
      )
    },
    handleClick(e) {
      if (e.index == 0) {
        this.isLogin = true
      } else {
        this.isLogin = false
      }
    },
    getCode() {
      getCodeImg().then((res) => {
        this.codeUrl = "data:image/gif;base64," + res.data.img
        this.loginForm.uuid = res.data.uuid
      })
    },
    getCookie() {
      const username = Cookies.get("username")
      const password = Cookies.get("password")
      const rememberMe = Cookies.get("rememberMe")
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      }
    },
    doLogin() {
      this.loading = true
      if (this.loginForm.rememberMe) {
        Cookies.set("username", this.loginForm.username, { expires: 30 })
        Cookies.set("password", encrypt(this.loginForm.password), {
          expires: 30,
        })
        Cookies.set("rememberMe", this.loginForm.rememberMe, { expires: 30 })
      } else {
        Cookies.remove("username")
        Cookies.remove("password")
        Cookies.remove("rememberMe")
      }
      this.$store
        .dispatch("Login", this.loginForm)
        .then(() => {
          this.$router.push({ path: this.redirect || "/" }).catch(() => {})
        })
        .catch(() => {
          this.loading = false
          this.getCode()
        })
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          if (this.isMobile) {
            this.doLogin()
          } else {
            this.$refs.verify.init()
          }
        }
      })
    },
    verifyChange(con) {
      // 拼图验证码回显
      if (!con.status) return

      this.loginForm.validUuid = con.validUuid
      this.doLogin()
      this.$refs.verify.show = false
    },
  },
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
#particles-js {
  width: 100%;
  height: calc(100% - 100px);
  position: absolute;
}
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  //background-image: url("../assets/images/login-background.jpg");
  background-color: orange;
  background-size: cover;
  position: relative;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #f9f8f8;
  width: 25%;
  min-width: 350px;
  padding: 25px 25px 5px 25px;
  position: absolute;
  z-index: 1111;
  margin: auto;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
.logo {
  position: fixed;
  width: 50%;
  top: 5%;
  img {
    width: 100%;
    // 图片不可选中
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    -khtml-user-select: none;
    user-select: none;
  }
}
.el-tabs {
  display: flex;
  justify-content: center;
}
.login_container_class {
  display: flex;
  justify-content: center;
  align-items: center;
}
.self-defined-classname {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  top: -10px;
}
</style>
